<doc>
  @author: 李百成
  @description： 长列表组件
</doc>
<template>
  <div class="infinite-list-warp">
    <div class="infinite-list-container" id="infinite-list-container" ref="infiniteWrapRef" @scroll="scrollEvent">
      <div class="infinite-list-phantom" :style="listStyle"></div>
      <ul class="infinite-list" :style="transformStyle" @click="onClick($event, 'burc')">
        <li class="infinite-list-item" :style="itemStyle" v-for="item in visibleData" :key="item.id">
          {{ item.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'infiniteList',
  components: {},
  props: {
    listData: {
      type: Array,
      default: () => [],
    },

    itemHeight: {
      type: Number,
      default: 30,
    },
  },
  data () {
    return {
      // 偏移量
      startOffset: 0,
      // 真实显示列表数据
      visibleData: [],
    }
  },

  computed: {
    // 列表总高度
    listStyle () {
      console.log('listHeight ', this.listData.length * this.itemHeight + 'px')
      return {
        height: this.listData.length * this.itemHeight + 'px',
      }
    },
    // 列表项样式
    itemStyle () {
      return {
        height: this.itemHeight + 'px',
        lineHeight: this.itemHeight + 'px',
      }
    },
    // 偏移量对应的style
    transformStyle () {
      return {
        transform: `translateY(${this.startOffset}px)`,
      }
    },
  },
  created () {},
  mounted () {
    this.updateVisibleData()
  },
  methods: {
    initData () {
      this.screenHeight = document.getElementById('infinite-list-container').clientHeight
      this.start = 0
      this.end = this.start + this.visibleCount
    },

    updateVisibleData (scrollTop = 0) {
      const screenHeight = document.getElementById('infinite-list-container').clientHeight
      // 可显示的列表项数
      const visibleCount = Math.ceil(screenHeight / this.itemHeight) + 2

      // 此时的开始索引
      const start = Math.floor(scrollTop / this.itemHeight)
      // 此时的结束索引
      const end = start + visibleCount

      this.visibleData = this.listData.slice(start, end)

      // 此时的偏移量
      this.startOffset = scrollTop - (scrollTop % this.itemHeight)
    },

    scrollEvent () {
      const scrollTop = document.getElementById('infinite-list-container').scrollTop
      this.updateVisibleData(scrollTop)
    },

    onClick (event) {
      console.log('event', event)
    },
  },
}
</script>

<style lang="less">
.infinite-list-warp {
  height: 100%;
  border: 3px solid palevioletred;
}
.infinite-list-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 3px solid paleturquoise;
}
.infinite-list-phantom {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  z-index: 1;
  background: #f00;
}
.infinite-list {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  z-index: 2;
  background: peachpuff;
}
.infinite-list-item {
  height: 50px;
  border: 1px solid palevioletred;
}
</style>
